package com.hefan.live.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hefan.live.bean.LiveRoomPersonVo;
import com.hefan.live.itf.LiveLogPersonService;
import com.hefan.live.itf.LivingRedisOptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 直播间用户处理
 * 
 * @author kevin_zhang
 *
 */
@Component("liveLogPersonService")
public class LiveLogPersonServiceImpl implements LiveLogPersonService {
	public Logger logger = LoggerFactory.getLogger(LiveLogPersonServiceImpl.class);

	@Resource
    LivingRedisOptService livingRedisOptService;

	/**
	 * 从redis获取直播间观看人数
	 * @param num
	 * @param userId
	 * @description 从liveUUid 直播间随机获取 num人，且不包含userId
	 * @author wangchao
	 * @create 2016/11/30 11:07
	 */
	@Override
	public List<Map<String, String>> getIdsFromRedisForLive(String authId, int num, String userId) {
		List<Map<String, String>> people = Lists.newArrayList();
		Random ra = new Random();
		try {
			//从直播间获取num人
			List<LiveRoomPersonVo> list = livingRedisOptService.getLivingUserList_SortedSet(authId, 1, num);
			logger.info("从主播id={}，获取{}人 list={}", authId, num, list.toString());
			if (!CollectionUtils.isEmpty(list)) {
				for (int i = 0; i < num; i++) {
					if (!CollectionUtils.isEmpty(list)) {
						int position = 0;
						if (list.size() > 1) {
							position = ra.nextInt(list.size() - 1);
						}
						LiveRoomPersonVo person = list.remove(position);
						logger.info("红包获奖人{}", JSON.toJSONString(person));
						//排除虚拟、机器人和发送人userId
						if (person != null && person.getUserType() <= 5 && !person.getUserId().equals(userId)) {
							Map<String, String> map = Maps.newHashMap();
							map.put("userId", person.getUserId());
							people.add(map);
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("获取红包中奖人数异常", e);
			return Lists.newArrayList();
		}
		return people;
	}
}